package com.hskn.hss.module.workgroup.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.entity.TreeEntity;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.workgroup.entity.WorkGroup;
import com.hskn.hss.module.workgroup.entity.WorkGroupFull;
import com.hskn.hss.module.workgroup.mapper.WorkGroupMapper;
import com.hskn.hss.module.workgroup.service.IWorkGroupService;
import com.hskn.hss.module.workkaoqin.entity.WorkKaoqin;
import com.hskn.hss.module.workkaoqin.mapper.WorkKaoqinMapper;
import com.hskn.hss.module.workkaoqin.service.IWorkKaoqinService;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-11
 */
@Service
public class WorkGroupServiceImpl extends ServiceImpl<WorkGroupMapper, WorkGroup> implements IWorkGroupService {

    @Autowired
    private IWorkKaoqinService workKaoqinService;
    @Resource
    private WorkGroupMapper workGroupMapper;
    @Resource
    private WorkKaoqinMapper workKaoqinMapper;
    @Resource
    private SysDepartMapper sysDepartMapper;



    @Override
    @DataScope(deptAlias = "depid", userAlias = "create_uid, update_uid")
    public JSONObject mList(BaseEntity entity, JSONObject params) throws HssException {
        JSONObject json = new JSONObject();
        QueryWrapper<WorkGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(WorkGroup::getCreateTime);
        String depid = params.getString("depid");
        if (StringUtils.isNotEmpty(depid)) {
            queryWrapper.lambda().eq(WorkGroup::getDepid, depid);
        }
        String module = params.getString("module");
        if (StringUtils.isNotEmpty(module)) {
            queryWrapper.lambda().eq(WorkGroup::getModule, module);
        }
        String kaoqinType = params.getString("kaoqinType");
        if (StringUtils.isNotEmpty(kaoqinType)) {
            queryWrapper.lambda().eq(WorkGroup::getKaoqinType, kaoqinType);
        }
        String name = params.getString("name");
        if (StringUtils.isNotEmpty(name)) {
            queryWrapper.lambda().like(WorkGroup::getName, name);
        }
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<WorkGroup> workGroupPage = new Page<>(page, size, true);
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        IPage<WorkGroup> iPage = workGroupMapper.selectPage(workGroupPage, queryWrapper);
        List<WorkGroup> workGroups = iPage.getRecords();
        List<WorkGroupFull> workGroupFulls = new ArrayList<>();
        for (WorkGroup workGroup : workGroups) {
            String wkIdsStr = workGroup.getKaoqinIds();
            String[] wkIds = wkIdsStr.split(",");
            QueryWrapper<WorkKaoqin> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().in(WorkKaoqin::getWorkKaoqinId, Arrays.asList(wkIds));
            List<WorkKaoqin> workKaoqins = workKaoqinMapper.selectList(queryWrapper1);
            WorkGroupFull workGroupFull = JSON.parseObject(JSON.toJSONString(workGroup), WorkGroupFull.class);
            workGroupFull.setKaoqins(workKaoqins);
            workGroupFulls.add(workGroupFull);
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("workGroups", workGroupFulls);
        return json;
    }

    @Override
    @Transactional
    public void mUpdate(JSONObject params) throws HssException {
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("workGroupId"))) {
            throw new HssException("参数错误");
        }
        WorkGroupFull workGroupFull = JSON.parseObject(params.toJSONString(), WorkGroupFull.class);
        List<WorkKaoqin> kaoqins = workGroupFull.getKaoqins();
        if (StringUtils.isNotEmpty(kaoqins) && kaoqins.size() > 0) {
            workKaoqinService.saveBatch(kaoqins);
        }
        String kaoqinIds = "";
        for (WorkKaoqin kaoqin : kaoqins) {
            kaoqinIds += kaoqin.getWorkKaoqinId() + ",";
        }
        kaoqinIds = kaoqinIds.replaceAll("(^,)|(,$)", "");
        WorkGroup workGroup = JSON.parseObject(params.toJSONString(), WorkGroup.class);
        workGroup.setKaoqinIds(kaoqinIds);
        workGroupMapper.updateById(workGroup);
    }

    @Override
    @Transactional
    public void add(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        WorkGroupFull workGroupFull = JSON.parseObject(params.toJSONString(), WorkGroupFull.class);
        workGroupFull.setCreateUid(uid);
        List<WorkKaoqin> kaoqins = workGroupFull.getKaoqins();
        if (StringUtils.isNotEmpty(kaoqins) && kaoqins.size() > 0) {
            workKaoqinService.saveBatch(kaoqins);
        }
        String kaoqinIds = "";
        for (WorkKaoqin kaoqin : kaoqins) {
            kaoqinIds += kaoqin.getWorkKaoqinId() + ",";
        }
        kaoqinIds = kaoqinIds.replaceAll("(^,)|(,$)", "");
        WorkGroup workGroup = JSON.parseObject(params.toJSONString(), WorkGroup.class);
        workGroup.setKaoqinIds(kaoqinIds);
        workGroupMapper.insert(workGroup);
    }


    @Override
    public WorkGroupFull detail(JSONObject params) throws HssException {
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("workGroupId"))) {
            throw new HssException("参数错误");
        }
        WorkGroup workGroup = workGroupMapper.selectById(params.getString("workGroupId"));
        if (StringUtils.isEmpty(workGroup)) {
            return null;
        }
        String wkIdsStr = workGroup.getKaoqinIds();
        String[] wkIds = wkIdsStr.split(",");
        QueryWrapper<WorkKaoqin> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(WorkKaoqin::getWorkKaoqinId, Arrays.asList(wkIds));
        List<WorkKaoqin> workKaoqins = workKaoqinMapper.selectList(queryWrapper);
        WorkGroupFull workGroupFull = JSON.parseObject(JSON.toJSONString(workGroup), WorkGroupFull.class);
        workGroupFull.setKaoqins(workKaoqins);
        return workGroupFull;
    }

    @Override
    public List<TreeEntity> tree() throws HssException {
        List<TreeEntity> treeList = sysDepartMapper.getTreeList();
        List<TreeEntity> userTree = workGroupMapper.getTree();
        treeList.addAll(userTree);
        List<TreeEntity> trees = TreeUtil.RecursiveAddress(treeList);
        return trees;
    }

    @Override
    public List<Map<String, Object>> treeSimple(JSONObject params) throws HssException {
        Integer module = params.getInteger("module");
        List<Map<String, Object>> list = workGroupMapper.getDepInfo(module);
        if (StringUtils.isNotEmpty(list) && list.size() > 0) {
            QueryWrapper<WorkGroup> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(module)) {
                queryWrapper.lambda().eq(WorkGroup::getModule, module);
            }
            List<WorkGroup> workGroups = workGroupMapper.selectList(queryWrapper);
            for (WorkGroup workGroup : workGroups) {
                String wkIdsStr = workGroup.getKaoqinIds();
                List<String> wkIds = StringUtils.isEmpty(wkIdsStr) ? new ArrayList<>() : Arrays.asList(wkIdsStr.split(","));
                QueryWrapper<WorkKaoqin> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.lambda().in(WorkKaoqin::getWorkKaoqinId, wkIds);
                List<WorkKaoqin> workKaoqins = workKaoqinMapper.selectList(queryWrapper2);
                WorkGroupFull workGroupFull = JSON.parseObject(JSON.toJSONString(workGroup), WorkGroupFull.class);
                workGroupFull.setKaoqins(workKaoqins);
                for (Map<String, Object> map : list) {
                    if (map.get("depid").equals(workGroupFull.getDepid())) {
                        if (!map.containsKey("children")) {
                            map.put("children", new ArrayList<>());
                        }
                        JSONArray children = JSON.parseArray(map.get("children").toString());
                        children.add(workGroupFull);
                        map.put("children", children);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public Map<String, WorkGroup> getWorkGroupMap(QueryWrapper<WorkGroup> workGroupQueryWrapper) {
        Map<String, WorkGroup> map = new HashMap<>();
        List<WorkGroup> list = workGroupMapper.selectList(workGroupQueryWrapper);
        if (list.isEmpty()) {
            return map;
        }
        return GroupingByUtils.getGroupingForMapEntity(list, WorkGroup::getWorkGroupId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
    }
}
